#-*- coding:utf-8 -*-
"""
解析脚本
"""
import os
import csv


class KeyMap(object):

    def __init__(self,path,Frame=24):
        super(KeyMap, self).__init__()
        self.Frame = Frame
        self.data = self.decodeKeyMap(path)



    def decodeKeyMap(self,path):
        data = {}
        with open(path,'r',encoding='utf8') as r:
            data = eval(r.read())

        return data

    def getKeys(self):

        return list(self.data.keys())

    def t2f(self,start_list,end_list):
        """
        时间序列转时间端
        :param start_list:
        :return: end_list
        """
        # if len(start_list) != len(end_list):
        #     end_list.append(start_list[-1])
        frames = []
        for start,end in zip(start_list,end_list):
            start_frame = int(start*self.Frame)
            end_frame = int(end*self.Frame)
            frames.append((start_frame,end_frame))
        return frames


    def getFrames(self,key):
        """
        传入想要查询的key，返回该key的所有Frame
        :param key:
        :return:
        """
        if key in self.data.keys():
            start = self.data[key]['start']
            end = self.data[key]['end']
            return self.t2f(start,end)
        else:
            return None

    def getAllFrames(self):
        """
        返回所有key，所有Frame
        :return:
        """
        key_frame = {}
        for key,data in self.data.items():
            frames = self.getFrames(key)
            key_frame[key] = frames

        return key_frame

    def toCSV(self,path):
        """
        将数据转成cvs格式
        :param path:
        :return:
        """

        keys = sorted(key_frame.keys())
        header = ['Key','Down','Up']


        rows =[]
        for key in keys:
            start_list = self.data[key]['start']
            end_list = self.data[key]['end']
            for start, end in zip(start_list, end_list):
                start_frame = int(start * self.Frame)
                end_frame = int(end * self.Frame)
                row_data = (key,start_frame,end_frame)
                rows.append(row_data)

        with open(path,'w') as w:
            w_csv = csv.writer(w)
            w_csv.writerow(header)
            w_csv.writerows(rows)



if __name__ == '__main__':

    km = KeyMap('key.map')
    key_frame = km.getAllFrames()
    print(key_frame)
    km.toCSV('keymap.csv')
    # keys = km.getKeys()

    # print(keys)
    # for i in keys:
    #     result = km.parse(i)
    #     print(i,result)